namespace SB2.Core;
/// <summary>
/// python 脚本运行
/// </summary>
public class ScriptWithPython : IDynamicFunction, ITransient
{
    /// <summary>
    /// 执行脚本
    /// </summary>
    /// <returns></returns>
    public async Task<object> RunAsync(DynamicFunctionExcDto param)
    {
        if (param.Script == null) throw new Exception("无效脚本");
        var _func = GetFunction(param.Script);
        await Task.FromResult(1);
        try
        {
            return _func(param.Param);
        }
        catch (Exception e)
        {
            throw new Exception($"脚本内执行失败：{e.Message}");
        }
    }
    /// <summary>
    /// 获取python 脚本内函数
    /// </summary>
    /// <param name="script"></param>
    /// <returns></returns>
    dynamic GetFunction(DynamicFunctionScript script)
    {
        var CodeString = script.GetCode();
        var functionName = string.IsNullOrEmpty(script.FunctionName) ? "main" : script.FunctionName;// 默认入口函数main
        try
        {
            var pythonEngine = IronPython.Hosting.Python.CreateEngine();
            var ReportScriptPath = pythonEngine.CreateScriptSourceFromString(CodeString);
            var code = ReportScriptPath.Compile();
            var scope = pythonEngine.CreateScope();
            code.Execute(scope);
            return scope.GetVariable(functionName);
        }
        catch (Exception e)
        {
            throw new Exception($"加载脚本失败：{e.Message}");
        }

    }
}
